package com.ld.zxw.Documents;

import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.BinaryPoint;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatPoint;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.util.BytesRef;
/**
 * 字段添加
 * @author Administrator
 *
 */
public class Documents {
	

	private Document document;
	

	public Documents() {
		document = new Document();
	}

	public void put(String key,Object val, String type, float boost){
		String value = "";
		if(val != null){
			value = val.toString();
		}
		addField(key, value, type, boost);
	}

	public Document getDocument(){
		return this.document;
	}
	
	
	
	/**
	 * 
	 * @param name key
	 * @param value val
	 * @param boost 权重
	 * @param type  字段类型
	 */
	@SuppressWarnings("deprecation")
	public void addField(String name, String value,String type,float boost){
		List<Field> fields = new ArrayList<>();
		String type_ = type.toLowerCase();
		switch (type_) {
		case "int":
			int point_i = Integer.parseInt(value);
			fields.add(new IntPoint(name, point_i));
			fields.add(new StoredField(name, point_i));
			fields.add(new NumericDocValuesField(name, point_i));
			break;
		case "float":
			float point_f = Float.valueOf(value);
			fields.add(new FloatPoint(name, point_f));
			fields.add(new StoredField(name, point_f));
			break;
		case "binary":
			byte[] point_b = value.getBytes();
			fields.add(new BinaryPoint(name, point_b));
			fields.add(new StoredField(name, point_b));
			break;
		case "double":
			double point_d = Double.valueOf(value);
			fields.add(new DoublePoint(name, point_d));
			fields.add(new StoredField(name, point_d));
			break;
		case "string":
			fields.add(new StringField(name, value, Field.Store.YES));
			fields.add(new SortedDocValuesField(name, new BytesRef(value)));
			break;
		case "text":
			TextField textField = new TextField(name, value, Field.Store.YES);
			textField.setBoost(boost);
			fields.add(textField);
			break;
		default:
			break;
		}
		int size = fields.size();
		for (int i = 0; i < size; i++) {
			document.add(fields.get(i));
		}
	}
}
